<?php

class PostController extends Controller
{
	/**
	 * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
	 * using two-column layout. See 'protected/views/layouts/column2.php'.
	 */
	//public $layout='//layouts/column2';

	/**
	 * @return array action filters
	 */
	public function filters()
	{
		return array(
			'accessControl', // perform access control for CRUD operations
			'postOnly + delete', // we only allow deletion via POST request
		);
	}

	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
	public function accessRules()
	{
		return $this->getRules();
	}

	/**
	 * Displays a particular model.
	 * @param integer $id the ID of the model to be displayed
	 */
	public function actionView()
	{
		print_r('<pre>');
            print_r($this->getRules());
            print_r('</pre>');
            exit();
	}

	
	/**
	 * Manages all models.
	 */
	public function actionAdmin()
	{
		$model=new PostModel('search');
		$model->unsetAttributes();  // clear any default values
		if(isset($_GET['PostModel']))
			$model->attributes=$_GET['PostModel'];

		$this->render('admin',array(
			'model'=>$model,
		));
	}

	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer $id the ID of the model to be loaded
	 * @return PostModel the loaded model
	 * @throws CHttpException
	 */
	public function loadModel($id)
	{
		$model=PostModel::model()->findByPk($id);
		if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}

	/**
	 * Performs the AJAX validation.
	 * @param PostModel $model the model to be validated
	 */
	protected function performAjaxValidation($model)
	{
		if(isset($_POST['ajax']) && $_POST['ajax']==='post-model-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}
        
        public function actionIndex(){
            //init page value
            $pagevals = array(
                'page_title' => "Quản trị bài viết",
                'subpage_title' => 'Danh sách bài viết',
                //'action' => 'post/abc'
            );
            
            //check input params and validate input
            $config = ConfigModel::model()->findByPk('1')->attributes;
            $paging_limit_number = $config['paging_limit_number'];
            $status = isset($_GET['status']) ? $_GET['status'] : 'active';
            $search_string = isset($_GET['search_string']) ? $_GET['search_string'] : '';
            $page_number = isset($_GET['page_number']) ? intval($_GET['page_number']) : 1;
            $position = isset($_GET['position']) ? $_GET['position'] : 'all';
            $category_id = isset($_GET['category_id']) ? $_GET['category_id'] : 'all';
            $hot_status = isset($_GET['hot_status']) ? $_GET['hot_status'] : 'all';
            $author_id = isset($_GET['author_id']) ? $_GET['author_id'] : 'all';
            $vote = isset($_GET['vote']) ? $_GET['vote'] : 'all';

            
            $condition = array();
            
            //validate input
            if($page_number <= 0 || is_numeric($page_number)!= true )$page_number=1;
            if($status != 'all'){ $condition['status'] = $status; }
            if($position != 'all'){$condition['position'] = $position;}
            if($category_id != 'all'){$condition['category_id'] = $category_id;}
            if($hot_status != 'all'){$condition['hot_status'] = $hot_status;}
            if($author_id != 'all'){$condition['author_id'] = $author_id;}
            if($vote != 'all'){$condition['vote'] = $vote;}

            
            $sort = array('hot_status'=>'desc','create_time'=>'desc');
            
            if($search_string == null || $search_string == ""){
                $data = PostModel::model()->getByPage($condition, $page_number, $paging_limit_number, $sort);
                $pagevals['total_row'] = PostModel::model()->countRow($condition);
            }else{
                $fields = array('title','short_intro','source','pageviews','start_time','end_time','position','vote');
                $data = PostModel::model()->SearchMultiField($search_string, $condition, $page_number, $paging_limit_number, $fields);
                $pagevals['total_row'] = PostModel::model()->countSearch($search_string, $condition, $fields);
            }
            
            if(is_array($data)){
                foreach($data as $key => $post){
                    $author = SystemAccountModel::model()->getByID($post['author_id']) ;
                    if($author != null){ 
                        $data[$key]['author'] = $author['username'];
                    }else{
                        $data[$key]['author']='';
                    }
                }
            }
            
            //get author name
            $author_filter_laber = array();
            $author_filter_id = PostModel::model()->getUnique('author_id');
            if(is_array($author_filter_id)){
                foreach($author_filter_id as $value){
                    $author_model = SystemAccountModel::model()->getByID($value['author_id']) ;
                    if($author_model != null){ 
                       $author_filter_laber[$value['author_id']]  = $author_model['username'];
                    }
                }
            }
            
            //get category name
            $category_filter_laber = array();
            $category_filter_id = PostModel::model()->getUnique('category_id');
            if(is_array($category_filter_id)){
                foreach($category_filter_id as $value){
                    $category_model = PCategoryModel::model()->getByID($value['category_id']) ;
                    if($category_model != null){ 
                       $category_filter_laber[$value['category_id']]  = $category_model['name'];
                    }
                }
            }
            
            $filter_fields = array(
                //'author'=>'asc',
                'status'=>'asc',
            );

            //process and render data 
            $pagevals['filter_label'] = $this->getFilterValue($filter_fields);
            $pagevals['filter_label']['author'] =  $author_filter_laber;
            $pagevals['filter_label']['category'] =  $category_filter_laber;
            
            $pagevals['page_number'] = $page_number;
            $pagevals['total_page'] = PostModel::model()->countPage($pagevals['total_row'], $paging_limit_number);
            $pagevals['row_start'] = PostModel::model()->get_start_row($pagevals['total_row'], $page_number, $paging_limit_number);
            $pagevals['row_end'] = PostModel::model()->get_end_row($pagevals['total_row'], $page_number, $paging_limit_number);
            $pagevals['status'] = $status;
            $pagevals['search_string'] = $search_string;
            $pagevals['position']= $position;
            $pagevals['author_id']= $author_id;
            $pagevals['hot_status']= $hot_status;
            $pagevals['category_id']= $category_id;
            $pagevals['vote']= $vote;


            $this->display("post/index", array('data'=>$data, 'pagevals'=>$pagevals) );
        }
        
        public function actionCreate()
	{
            
            $pagevals = array(
                'page_title' => "Quản trị bài viết",
                'subpage_title' => 'Tạo bài viết mới',
                //'action' => 'post/abc'
            );
            
            //get category name
            $category_filter_laber = array();
            $categories = PCategoryModel::model()->getAll();
            if(is_array($categories)){
                foreach($categories as $value){
                    if($value != null){ 
                       $category_filter_laber[$value['id']]  = $value['name'];
                    }
                }
            }
            $pagevals['selection_label']['category'] = $category_filter_laber;
            
            
            ///--------------------------
            $time=time();
            $pagevals['time']=$time;
            $post = new PostModel;
            if(isset($_POST['title'])){
                
                $min_start = isset($_POST['min_start_time']) ? $_POST['min_start_time'] : 0;
                $hour_start = isset($_POST['hour_start_time']) ? $_POST['hour_start_time'] : 0;
                $day_start = isset($_POST['day_start_time']) ? $_POST['day_start_time'] : 0;
                $mon_start = isset($_POST['mon_start_time']) ? $_POST['mon_start_time'] : 0;
                $year_start = isset($_POST['year_start_time']) ? $_POST['year_start_time'] : 0;
                $min_end = isset($_POST['min_end_time']) ? $_POST['min_end_time'] : 0;
                $hour_end = isset($_POST['hour_end_time']) ? $_POST['hour_end_time'] : 0;
                $day_end = isset($_POST['day_end_time']) ? $_POST['day_end_time'] : 0;
                $mon_end = isset($_POST['mon_end_time']) ? $_POST['mon_end_time'] : 0;
                $year_end = isset($_POST['year_end_time']) ? $_POST['year_end_time'] : 0;
                
                $start_time = mktime(intval($hour_start),intval($min_start),0,intval($mon_start),intval($day_start),intval($year_start));
                $end_time = mktime(intval($hour_end),intval($min_end),0,intval($mon_end),intval($day_end),intval($year_end));
                //print_r('<pre>');
                //print_r($post->attributes);
                //print_r($_POST);
                //print_r('</pre>');
                //exit();
                $post->attributes = array(
                            //'id' => 'ID',
                            'title' => $_POST['title'],
                            'slug' => $_POST['slug'],
                            'short_intro' => $_POST['short_intro'],
                            'content' => $_POST['content'],
                            'source' => $_POST['source'],
                            'tags' => $_POST['tags'],
                            'thumb' => $_POST['thumb'],
                            //'pageviews' => $_POST['pageviews'],
                            'position' => $_POST['position'],
                            'vote' => $_POST['vote'],
                            'hot_status'=>$_POST['hot_status'],
                            'author_id' => Yii::app()->user->id,
                            'category_id'=>$_POST['category_id'],
                            'status' => $_POST['status'],
                            'start_time' => $start_time,
                            'end_time' => $end_time,
                            'create_time' => $time,
                            'update_time' => $time,
                        );
                if($post->save(false)){
                    $this->redirect(array('index','status'=>$_POST['status']));
                }
            }
            $this->display("post/create", array('pagevals'=>$pagevals));
	}
        

        public function actionEdit($id)
	{
            if(!isset($_GET['id'])){
                die('Post not found');
            } 
            $pagevals = array(
                'page_title' => "Quản trị bài viết",
                'subpage_title' => 'Tạo bài viết mới',
                //'action' => 'post/abc'
            );

            //-------------------------------
            //get post data
            $post = PostModel::model()->findByPk($id);
            if(!is_object($post)){
                die('Post not found');
            }
            
            //get category name
            $category_filter_laber = array();
            $categories = PCategoryModel::model()->getAll();
            if(is_array($categories)){
                foreach($categories as $value){
                    if($value != null){ 
                       $category_filter_laber[$value['id']]  = $value['name'];
                    }
                }
            }
            $pagevals['selection_label']['category'] = $category_filter_laber;
            
            ///--------------------------
            $time=time();
            if(isset($_POST['title'])){
                
                
                $min_start = isset($_POST['min_start_time']) ? $_POST['min_start_time'] : 0;
                $hour_start = isset($_POST['hour_start_time']) ? $_POST['hour_start_time'] : 0;
                $day_start = isset($_POST['day_start_time']) ? $_POST['day_start_time'] : 0;
                $mon_start = isset($_POST['mon_start_time']) ? $_POST['mon_start_time'] : 0;
                $year_start = isset($_POST['year_start_time']) ? $_POST['year_start_time'] : 0;
                $min_end = isset($_POST['min_end_time']) ? $_POST['min_end_time'] : 0;
                $hour_end = isset($_POST['hour_end_time']) ? $_POST['hour_end_time'] : 0;
                $day_end = isset($_POST['day_end_time']) ? $_POST['day_end_time'] : 0;
                $mon_end = isset($_POST['mon_end_time']) ? $_POST['mon_end_time'] : 0;
                $year_end = isset($_POST['year_end_time']) ? $_POST['year_end_time'] : 0;
                
                $start_time = mktime(intval($hour_start),intval($min_start),0,intval($mon_start),intval($day_start),intval($year_start));
                $end_time = mktime(intval($hour_end),intval($min_end),0,intval($mon_end),intval($day_end),intval($year_end));
                
                $post->attributes = array(
                            //'id' => 'ID',
                            'title' => $_POST['title'],
                            'slug' => $_POST['slug'],
                            'short_intro' => $_POST['short_intro'],
                            'content' => $_POST['content'],
                            'source' => $_POST['source'],
                            'tags' => $_POST['tags'],
                            'thumb' => $_POST['thumb'],
                            //'pageviews' => $_POST['pageviews'],
                            'position' => $_POST['position'],
                            'vote' => $_POST['vote'],
                            'hot_status'=>$_POST['hot_status'],
                            //'author_id' => 'Author',
                            'category_id'=>$_POST['category_id'],
                            'status' => $_POST['status'],
                            'start_time' => $start_time,
                            'end_time' => $end_time,
                            //'create_time' => $time,
                            'update_time' => $time,
                        );
                if($post->save(false)){
                    $this->redirect(array('post/index','status'=>$_POST['status']));
                }
            }
            
            
            
            $this->display("post/edit", array('pagevals'=>$pagevals,'data'=>$post->attributes));
        }

        
        public function doAcion($status,$data){
            $i = 0;
            $time = time();
            $game_id = explode(';', $data);
            if(sizeof($game_id) == 0){
                echo 0;
            }
            else{
                foreach($game_id as $value){
                    if($value != 0){
                        $result = PostModel::model()->modify($value,array('status'=>$status,'update_time'=>$time));
                        if($result == true){
                            $i++;
                        }
                    }
                }
                echo $i;
            }
        }
        
        
        public function actionCopy(){
            if(isset($_POST['game_id'])){
                $i = 0;
                $game_id = explode(';', $_POST['game_id']);
                if(sizeof($game_id) == 0){
                    echo 0;
                }
                else{
                    foreach($game_id as $value){
                        if($value != 0){
                            $result = PostModel::model()->copy($value);
                            if($result == true){
                                $i++;
                            }
                        }
                    }
                    echo $i;
                }
            }
        }
        
        public function actionRemove(){
            if(isset($_POST['remove_ids'])){
                $this->doAcion('deleted', $_POST['remove_ids']);
            }
            if(isset($_POST['id'])){
                $result = PostModel::model()->modify($_POST['id'],array('status'=>'deleted','update_time'=>time()));
                if($result == true) echo 'success';
            }
            
        }
        
        public function actionPending(){
            if(isset($_POST['pending_ids'])){
                $this->doAcion('pending', $_POST['pending_ids']);
            }
            if(isset($_POST['id'])){
                $result = PostModel::model()->modify($_POST['id'],array('status'=>'pending','update_time'=>time()));
                if($result == true) echo 'success';
            }
            
        }
        
        public function actionApprove(){
            if(isset($_POST['approve_ids'])){
                $this->doAcion('approved', $_POST['approve_ids']);
            }
            if(isset($_POST['id'])){
                $result = PostModel::model()->modify($_POST['id'],array('status'=>'approved','update_time'=>time()));
                if($result == true) echo 'success';
            }
            
        }
        
        public function actionActive(){
            if(isset($_POST['active_ids'])){
                $this->doAcion('active', $_POST['active_ids']);
            }
            if(isset($_POST['id'])){
                $result = PostModel::model()->modify($_POST['id'],array('status'=>'active','update_time'=>time()));
                if($result == true) echo 'success';
            }
            
        }
        
        public function actionBlock(){
            if(isset($_POST['block_ids'])){
                $this->doAcion('blocked', $_POST['block_ids']);
            }
            
            if(isset($_POST['id'])){
                $result = PostModel::model()->modify($_POST['id'],array('status'=>'blocked','update_time'=>time()));
                if($result == true) echo 'success';
            }
            
        }
        
        public function actionRestore(){
            if(isset($_POST['restore_ids'])){
                $this->doAcion('pending', $_POST['restore_ids']);
            }
            if(isset($_POST['id'])){
                $result = PostModel::model()->modify($_POST['id'],array('status'=>'pending','update_time'=>time()));
                if($result == true) echo 'success';
            }
            
        }
        
        public function getFilterValue($fields){
            if(is_array($fields)){
                $result = array();
                foreach($fields as $key => $value){
                    $temp = PostModel::model()->getUnique($key, $value);
                    if(is_array($temp)){
                        foreach($temp as $val){
                            if($val[$key] !=null && $val[$key]!=''){
                                $result[$key][]= $val[$key];
                            }
                        }
                    }
                }
                return $result;
            }else return null;
        }
}
